package com.zou.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 * 给定一个target,返回其下表之和
 */

public class Mission1 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        System.out.println(twoSum(nums, target));
        System.out.println(twoSum2(nums, target));
    }

    public static int[] twoSum2(int[] nums, int target){

        for(int i = 0;i<nums.length;i++){
            int a = nums[i];
            for(int j = i;j<nums.length;j++){

                if(a+nums[j]==target){
                    System.out.println(i+" "+j);
                    return new int[]{i,j};
                }
            }
        }
        return new int[]{};

    }

    /**
     * 哈希表法
     * 将target-x的时间存储起来
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (countMap.containsKey(target - nums[i])) {
                System.out.println(i+" "+countMap.get(target-nums[i]));
                return new int[]{countMap.get(target-nums[i]),i};
            }
            countMap.put(nums[i], i);
        }
        return new int[]{};
    }
}
